package com.dynamic.mybatis.core.toolkit;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ClassUtils;
import com.dynamic.mybatis.core.metadata.MappedStatementField;
import com.dynamic.mybatis.core.metadata.MappedStatementFieldValidator;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.beans.BeanMap;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.beans.PropertyDescriptor;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.*;

/**
 * @Description 底层使用cglib拷贝， 注意对象属性的set方法使用Builder模式无法进行拷贝
 * @Author xs
 * @Date 2021/11/10 18:01
 */
public class BeanUtils {
    static ObjectMapper objectMapper = new ObjectMapper();


    public static byte[] serialize(Object bean) {
        try (
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        ){
            objectOutputStream.writeObject(bean);
            objectOutputStream.flush();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw  new RuntimeException(e);
        }
    }

    public static  <T> T deserialize(byte[] bytes) {
        try (
            ByteArrayInputStream byteArrayOutputStream = new ByteArrayInputStream(bytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayOutputStream);
        ){
         return (T) objectInputStream.readObject();
        } catch (Exception e) {
            throw  new RuntimeException(e);
        }
    }

    public static <T> T serializeCopy(Object bean){
        return BeanUtils.deserialize(BeanUtils.serialize(bean));
    }

    public static <T> T serializeJacksonCopy(Object bean) {
        return  (T) deserializeJackson(serializeJackson(bean),bean.getClass());
    }


    public static byte[] serializeJackson(Object bean) {
        try {
             return objectMapper.writeValueAsBytes(bean);
        } catch (Exception e) {
           throw  new RuntimeException(e);
        }
    }

    public static  <T> T deserializeJackson(byte[] bytes,Class<T> beanClass) {
       try  {
            return (T) objectMapper.readValue(bytes,beanClass);
       } catch (Exception e) {
            throw  new RuntimeException(e);
       }
    }



    public static Map beanToMap(Object bean){
        return bean == null ? null : bean instanceof  Map ? (Map) bean : BeanMap.create(bean);
    }

    public static <T> T copy(T bean) {
        T target =  ClassUtils.newInstance((Class<T>) bean.getClass());
        BeanCopier.create(bean.getClass(),bean.getClass(),false).copy(bean,target,null);
        return target ;
    }


    public static <S,T> T copy(S source,T target) {
        return copy(source,target,Boolean.TRUE);
    }


    public static <S,T> T copy(S source,T target,String... ignoreProperties) {
        return copy(source,target,Boolean.TRUE,ignoreProperties);
    }

    public static <S,T> T copy(S source,T target,boolean ignoreEmpty,String... ignoreProperties) {
        Map targetMap = copyGetMap(source,target,ignoreEmpty,ignoreProperties);
        return  getBean(targetMap);
    }
    public static <T> T getBean(Map map){
        return  (T) (map instanceof Map && !(map instanceof BeanMap) ? map : ((BeanMap)map).getBean());
    }


    public static <T> Map copyGetMap(T bean) {
        return  copyGetMap(bean,ClassUtils.newInstance((Class<T>) bean.getClass()),Boolean.TRUE);
    }

    public static <T> Map copyGetMap(T source,T target,boolean ignoreEmpty,String... ignoreProperties) {
        Map sm = beanToMap(source);
        Map tm = beanToMap(target);
        if(sm == null){
            return  tm;
        }
        Map  temp;
        if(ignoreEmpty){
            temp  = new MyHashMap(ignoreProperties);
            temp.putAll(sm);
        }else {
            temp = sm;
        }
        tm.putAll(temp);
        return tm;
    }

    static class  MyHashMap<K,V> extends HashMap<K,V>{
       private Object[] ignoreProperties;

        public MyHashMap(Object[] ignoreProperties) {
            this.ignoreProperties = ignoreProperties;
        }

        public MyHashMap() {
        }

        @Override
        public void putAll(Map<? extends K, ? extends V> m) {
             for(Map.Entry e : m.entrySet()){
                 if(StringUtils.isNotEmpty(e.getValue()) && (ignoreProperties == null || ignoreProperties.length < 1 || Arrays.binarySearch(ignoreProperties,e.getKey()) < 0)){
                    super.put((K)e.getKey(),(V) e.getValue());
                 }
             }
        }
    }


    public static String[] getNullPropertyNames(Object source) {
        BeanWrapper src = new BeanWrapperImpl(source);
        PropertyDescriptor[] pds = src.getPropertyDescriptors();
        Set<String> emptyNames = new HashSet<>();
        for (PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null){
                emptyNames.add(pd.getName());
            }
        }
        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    /**
     　* @Description: 忽略source中值为空的属性拷贝
     　*/
    public static <T> T copyProperties(T source, T target){
        org.springframework.beans.BeanUtils.copyProperties(source,target,getNullPropertyNames(source));
        return target;
    }


    public static void main(String[] args){

        Boolean bean = true;

        Map map = BeanUtils.beanToMap(bean);

        System.out.println(map);

    }





    public static Object getValueByPath(Map<String, Object> map, String path) {
        if (path == null || path.length() == 0) {
            return null;
        }
        String[] paths = path.split("\\.");
        Object newObj = null;

        for (int i = 0; i < paths.length; i++) {
            String s = paths[i];
            if (i == 0) {
                newObj = map.get(s);
                continue;
            }
            newObj = getObject(newObj, s);

        }
        return newObj;
    }

    private static Object getObject(Object newObj, String s) {
        if (newObj instanceof Map) {
            return ((Map) newObj).get(s);
        }
        if (newObj instanceof List) {
            List<Object> list = new ArrayList<>();
            List<Object> o = (List<Object>) newObj;
            for (Object object : o) {
                list.add(getObjectFromList(object, s));
            }
            return list;
        }
        if (newObj instanceof JSONObject) {
            return ((JSONObject) newObj).getInnerMap().get(s);
        }
        if (newObj instanceof JSONArray) {
            List<Object> list = new ArrayList<>();
            List<Map> o = (List<Map>) newObj;
            for (Map map1 : o) {
                list.add(map1.get(s));
            }
            return list;
        }
        return newObj;
    }

    public static Object getObjectFromList(Object object, String s) {
        if (object instanceof Map) {
            return ((Map) object).get(s);
        }
        if (object instanceof List) {
            List<Object> list = new ArrayList<>();
            List<Object> o1 = (List<Object>) object;
            for (Object o2 : o1) {
                list.add(getObjectFromList(o2, s));
            }
            return list;
        }
        return object;
    }


}